Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

283
Views
Switch statement within function returns "undefined" for no obvious reason

I am trying to create a simplistic function which uses a switch statement to return a weighted number. For my use case, the solution is most befitting, however I am getting "undefined" as the result for no obvious reasons. If anyone could point out the mistake, I'm making.

function randomCase() {
  let n = Math.floor(Math.random() * 100);

  switch (n) {
    case n < 70:
      return 1;
    case n < 80:
      return 2;
    case n < 90:
      return 3;
    case n < 100:
      return 4;
  }
}

temp = randomCase();

console.log(temp);

I tried to debug with Chrome developer tool and figure out what might be causing this, but of no avail. It seems there is something obvious I'm missing. (Still learning JS)

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

As VLAZ mentioned in the comments, a switch statement checks for equality.

You'll want to use an if statement instead:

function randomCase() {
  let n = Math.floor(Math.random() * 100);

  if (n < 70) {
    return 1;
  } else if (n < 80) {
    return 2;
  } else if (n < 90) {
      return 3;
  } else if (n < 100) {
      return 4;
  }
}

temp = randomCase();

console.log(temp);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!